// @PLUGIN Captures touch events on mobile devices to reduce delay.
jQuery.event.special.tap = {
    setup: function (a, b) {
        var c = this,
            d = jQuery(c);
        if (window.Touch) {
            d.bind("touchstart", jQuery.event.special.tap.onTouchStart);
            d.bind("touchmove", jQuery.event.special.tap.onTouchMove);
            d.bind("touchend", jQuery.event.special.tap.onTouchEnd)
        } else {
            d.bind("click", jQuery.event.special.tap.click)
        }
    },
    click: function (a) {
        a.type = "tap";
        jQuery.event.handle.apply(this, arguments)
    },
    teardown: function (a) {
        if (window.Touch) {
            $elem.unbind("touchstart", jQuery.event.special.tap.onTouchStart);
            $elem.unbind("touchmove", jQuery.event.special.tap.onTouchMove);
            $elem.unbind("touchend", jQuery.event.special.tap.onTouchEnd)
        } else {
            $elem.unbind("click", jQuery.event.special.tap.click)
        }
    },
    onTouchStart: function (a) {
        this.moved = false
    },
    onTouchMove: function (a) {
        this.moved = true
    },
    onTouchEnd: function (a) {
        if (!this.moved) {
            a.type = "tap";
            jQuery.event.handle.apply(this, arguments)
        }
    }
};
// @PLUGIN Notifications
(function ($) {
    $.notification = function (settings) {
       	var con, notification, hide, image, right, left, inner;
        
        settings = $.extend({
        	title: undefined,
        	content: undefined,
            timeout: HEIVR_LOGIN_MOBILE ? 3000 : 0,
            img: undefined,
            border: true,
            fill: false,
            showTime: false,
            click: undefined,
            icon: undefined,
            color: undefined,
            error: false
        }, settings);
        
        con = $("#notifications");
        if (!con.length) {
            con = $("<div>", { id: "notifications" }).appendTo($("#overlays"))
        };
        
		notification = $("<div>");
        notification.addClass("notification animated fadeInLeftMiddle fast");
        
        if(settings.error == true) {
        	notification.addClass("error");
        }
        
        if( $("#notifications .notification").length > 0 ) {
        	notification.addClass("more");
        } else {
        	con.addClass("animated flipInX").delay(1000).queue(function(){ 
        	    con.removeClass("animated flipInX");
        			con.clearQueue();
        	});
        }
        
        hide = $("<div>", {
			click: function () {
				 
				
				if($(this).parent().is(':last-child')) {
				    $(this).parent().remove();
				    $('#notifications .notification:last-child').removeClass("more");
				} else {
					$(this).parent().remove();
				}
			}
		});
		
		hide.addClass("hide");

		left = $("<div class='left'>");
		right = $("<div class='right'>");
		
		if(settings.title != undefined) {
			var htmlTitle = "<h2>" + settings.title + "</h2>";
		} else {
			var htmlTitle = "";
		}
		
		if(settings.content != undefined) {
			var htmlContent = settings.content;
		} else {
			var htmlContent = "";
		}
		
		inner = $("<div>", { html: htmlTitle + htmlContent });
		inner.addClass("inner");
		
		inner.appendTo(right);
		
		if (settings.img != undefined) {
			image = $("<div>", {
				style: "background-image: url('"+settings.img+"')"
			});
		
			image.addClass("img");
			image.appendTo(left);
			
			if(settings.border==false) {
				image.addClass("border")
			}
			
			if(settings.fill==true) {
				image.addClass("fill");
			}
			
		} else {
			if (settings.icon != undefined) {
				var iconType = settings.icon;
			} else {
				if(settings.error!=true) {
					var iconType = '"';
				} else {
					var iconType = '!';
				}
			}	
			icon = $('<div class="icon">').html(iconType);
			
			if (settings.color != undefined) {
				icon.css("color", settings.color);
			}
			
			icon.appendTo(left);
		}

        left.appendTo(notification);
        right.appendTo(notification);
        
        hide.appendTo(notification);
        
        function timeSince(time){
        	var time_formats = [
        	  [2, "1 秒", "1 second from now"], // 60*2
        	  [60, "秒", 1], // 60
        	  [120, "1 分钟", "1 minute from now"], // 60*2
        	  [3600, "分钟", 60], // 60*60, 60
        	  [7200, "1 小时", "1 hour from now"], // 60*60*2
        	  [86400, "hours", 3600], // 60*60*24, 60*60
        	  [172800, "One day", "tomorrow"], // 60*60*24*2
        	  [604800, "days", 86400], // 60*60*24*7, 60*60*24
        	  [1209600, "One week", "next week"], // 60*60*24*7*4*2
        	  [2419200, "weeks", 604800], // 60*60*24*7*4, 60*60*24*7
        	  [4838400, "One month", "next month"], // 60*60*24*7*4*2
        	  [29030400, "months", 2419200], // 60*60*24*7*4*12, 60*60*24*7*4
        	  [58060800, "One year", "next year"], // 60*60*24*7*4*12*2
        	  [2903040000, "years", 29030400], // 60*60*24*7*4*12*100, 60*60*24*7*4*12
        	  [5806080000, "One century", "next century"], // 60*60*24*7*4*12*100*2
        	  [58060800000, "centuries", 2903040000] // 60*60*24*7*4*12*100*20, 60*60*24*7*4*12*100
        	];
        	
        	var seconds = (new Date - time) / 1000;
        	var token = "ago", list_choice = 1;
        	if (seconds < 0) {
        		seconds = Math.abs(seconds);
        		token = "from now";
        		list_choice = 1;
        	}
        	var i = 0, format;
        	
        	while (format = time_formats[i++]) if (seconds < format[0]) {
        		if (typeof format[2] == "string")
        			return format[list_choice];
        	    else
        			return Math.floor(seconds / format[2]) + " " + format[1];
        	}
        	return time;
        };
        
        if(settings.showTime != false) {
        	var timestamp = Number(new Date());
        	
        	timeHTML = $("<div>", { html: "<strong>" + timeSince(timestamp) + "</strong> 前" });
        	timeHTML.addClass("time").attr("title", timestamp);
        	timeHTML.appendTo(right);
        	
        	setInterval(
	        	function() {
	        		$(".time").each(function () {
	        			var timing = $(this).attr("title");
	        			$(this).html("<strong>" + timeSince(timing) + "</strong> 前");
	        		});
	        	}, 4000)
        	
        }

        notification.hover(
        	function () {
            	hide.show();
        	}, 
        	function () {
        		hide.hide();
        	}
        );
        
        notification.prependTo(con);
		notification.show();

        if (settings.timeout) {
            setTimeout(function () {
            	var prev = notification.prev();
            	if(prev.hasClass("more")) {
            		if(prev.is(":first-child") || notification.is(":last-child")) {
            			prev.removeClass("more");
            		}
            	}
	        	notification.remove();
            }, settings.timeout)
        }
        
        if (settings.click != undefined) {
        	notification.addClass("click");
            notification.bind("click", function (event) {
            	var target = $(event.target);
                if(!target.is(".hide") ) {
                    settings.click.call(this)
                }
            })
        }
        return this
    }
})(jQuery);
$.initializeLogin = function() {
	// Update
	window.addEventListener("load", function (a) {
		window.applicationCache.addEventListener("updateready", function (a) {
			if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
				window.applicationCache.swapCache();
		            
				$.notification( 
					{
						title: 'An update has been installed!',
		            	content: 'Click here to reload.',
		            	icon: "u",
		            	click: function() {
		            		window.location.reload();
		            	}
		            }
		        );
		            
			}
		}, false);
	    
		    window.applicationCache.addEventListener("downloading", function (a) {
		        if (window.applicationCache.status == window.applicationCache.DOWNLOADING) {
		    		$.notification( 
		    			{
		    				title: 'Latest version is being cached',
		    				content: 'Only takes a few seconds.',
		    				icon: "H"
		    			}
		    		);
		    	}
		    }, false);

		}, false);
	// Adding overlay to the body
	$("body").addClass("welcome").append('<div id="overlays"></div>');
	
	// Welcome notification
	if( !HEIVR_LOGIN_MOBILE ){
		$.notification({
				title: "欢迎回到黑晶OA系统",
				content: "请选择一个用户!",
				img: "/static/pastel/demo/cloud.png",
				border: false
			}
		);
	}
	// Adding animation to the user avatars.
	$("#users").addClass("animated flipInY");
	
	$(".plus").on("click", function() {
		var avatar = $('<a data-username="" href="javascript:void(0);" class="avatar" data-avatar="/static/pastel/demo/autumn.jpg" />');
		avatar.css("background-image", "url("+ avatar.attr("data-avatar") +")");
		$("#avatars").append(avatar);
		avatar.addClass("animated bounceInDown").delay(1000).queue(function(){ 
			$(this).removeClass("animated bounceInDown");
			$(this).clearQueue();
			$(this).click();
		});
		$(this).remove();
	});
		/*
	$('#avatars').on('mousedown', '.avatar.pin', function(e) {
		var box = $(this);
		var AX = e.pageX;
		var AY = e.pageY;
		var id = $(this).attr("data-id");
        $(document).mousemove(function(e) {
			var X = e.pageX;
			var Y = e.pageY;
			Y = (Y && Y >= 1) ? (Y <= 752 ? Y : 752) : 0;
			X = (X && X >= 1) ? (X <= 1008 ? X : 1008) : 0;
			var CG = Math.abs(Y-AY);
			if( CG >= 60 ){
				removeUser(box, true);
				$(document).unbind("mousemove");
			}
        });
		$(document).bind('click', function(){
			$(document).unbind("mousemove");
		});
    });
		*/
	// Reveal login form when an avatar is clicked
	$('#avatars').on('click', '.avatar', function(event) {
		var obj = $(this);
		var id = obj.attr('data-id');
		var pin = $(this).hasClass('pin');
		
		if( pin ){
			if( event.offsetX > 105 || event.offsetY > 105 ){
				removeUser(obj);
				event.stopPropagation();
				return false;
			}
		}

		var dataname = obj.attr('data-username');
		var authcode = obj.attr('data-authcode');
		if( HEIVR_LOGIN_MOBILE && pin && authcode.length > 10 ){
			$.notification({
				title: "Hi, " + (obj.attr("data-realname") ? $(this).attr("data-realname") : $(this).attr("data-username")),
				content: "系统正在验证设备有效性...",
				img: obj.attr("data-avatar"),
				fill: true,
				showTime: true
			});
			$.ajax({
				type : 'POST',
				url : 'login.php'+location.search,
				data : {
					username : dataname,
					password : null,
					authcode : authcode
				},
				dataType : 'json',
				success : function(json){
					if( json.error ){
						console.log(json.data);
						var list = getUsers();
						if( list[id] ){
							list[id]['authcode'] = '';
						}
						obj.attr('data-authcode', '');
						setDatas(list);
						obj.click();
					}else{
						LoginSuccess(json);
					}
				}
			});
			return false;
		}
		$.notification({
			title: "Hi, " + (obj.attr("data-realname") ? $(this).attr("data-realname") : $(this).attr("data-username")),
			content: "欢迎使用黑晶OA系统，请输入您的HeivrID以及密码授权验证.",
			img: obj.attr("data-avatar"),
			fill: true,
			showTime: true
		});
		$("#password .input.username .avatar").remove();
		var avatar = $(this).clone().wrap('<div>').parent().html();
		$("#password .input.username").append(avatar);
		$("#password .input.username input").attr( "value", dataname );
		
		$("#users").addClass("animated flipOutY").delay(1000).queue(function(){ 
			$(this).removeClass();
			$(this).hide();
			$(this).clearQueue();
		});
		$("#password").removeClass().show();
		if( dataname ){
			$("#password .input.password input").focus();
		}else{
			$('.heivrid-input').focus();
		}
	});

	$('.heivrid-input').on('blur', function(){
		var heivrid = $(this).val();
		if( heivrid ){
			$.ajax({
				url : 'avatar.php?heivrid='+heivrid+'&jsonp=yes',
				dataType : 'json',
				success : function(json){
					if( json.data != null ){
						$('.username .avatar').css("background-image", "url("+ json.data +")")
					}
				}
			});
		}
	});
	
	$("#password a.back").on("click", function() {
		$("#users").removeClass().addClass("animated flipInY active").show();
		$("#password").addClass("animated fadeOutUp").delay(1000).queue(function(){ 
			$(this).removeClass();
			$(this).hide();
			$(this).clearQueue();
		});
	});
	
	$("#password button").on("click", function() {
		forgot();
	});
	
	$("#password .input.password input").keyup(function(event) {
		if (event.which == 13) {
			forgot();
		}
	});

	function forgot() {
		var heivrid = $('.heivrid-input').val();
		var password = $('.password-input').val();
		var remark = $('input:radio[name="remark"]:checked').attr('data-type');

		if( heivrid && password ){
			$.ajax({
				type : 'POST',
				url : 'login.php'+location.search,
				data : {
					username : heivrid,
					password : password,
					remark : remark,
				},
				dataType : 'json',
				success : function(json){
					if( json.error != 0 ){
						$.notification({
							title: '黑晶验证授权系统警告',
							content: json.data,
							icon : '!'
						});
						$("#password").removeClass('fadeInDown wobble');
						$("#password").addClass('wobble').delay(1000).queue(function(){ 
							$(this).clearQueue();
						});
						$('.password-input').focus();
					}else{
						LoginSuccess(json);
					}

				}
			});
		}else{
			$.notification(
				{
					title: "警告",
					content: "用户名或密码为空！",
					icon: "!"
				}
			);
			$("#password").removeClass('fadeInDown wobble');
			$("#password").addClass('wobble').delay(1000).queue(function(){ 
				$(this).clearQueue();
			});
		}
/*
		if($("#password .input.password input").val() != '') {
			$.notification(
				{
					title: "密码错误",
					content: "您输入的密码有误",
					icon: "!"
				}
			);
			$("#password").removeClass().addClass("animated wobble").delay(1000).queue(function(){ 
				$(this).attr('class', 'animated fadeInDown');
				$(this).clearQueue();
			});
			$("#password .input.password input").attr("value", "");
		} else {
			document.location.href = "home.html";
		}
*/
	}
};

function LoginSuccess(json){
	$.notification({
		title: '黑晶验证授权系统提示',
		content: '验证成功...页面正在加载',
		icon : '√'
	});
	$('.plus').hide();
	$('#avatars').html('<a data-username="" data-avatar="'+json.data.avatar+'" href="javascript:void(0);" class="avatar pin avatar"></a>');
	$('#avatars a').css("background-image", "url("+ json.data.avatar +")").delay(1000).animate({
		top : -9999
	}, 2500);
	$('.back').click();
	setUser(json.data);
	var remark = $('input:radio[name="remark"]:checked').attr('data-type');
	if (remark==1){
		window.location.href = json.data.redirectURL || './';
	}else{
		window.location.href = "http://oa.heivr/admin/coindex.php";
	}
	
}

function removeUser(obj, top){
	delUser(obj.attr('data-id'));
	var speed = top ? 1000 : 1000;
	obj.fadeOut(500, function(){
		obj.remove();
		if( $('.avatar.pin').length <= 0 ){
			$('.plus').click();
		}
	});
}

function getUsers(){
	var list = getcookie('heivr_login_list');
		list = list ? $.evalJSON(list) : {};
	return list;
}

function setUser(admin){
	var list = getUsers();
	if( admin ){
		list[admin.id] = {
			heivrid : admin.username,
			name : admin.realname ? admin.realname : admin.username,
			avatar : admin.avatar,
			authcode : admin.authcode ? admin.authcode : null
		};
	}
	setDatas(list);
}

function setDatas(list){
	var encoded = $.toJSON(list);
	setcookie('heivr_login_list', encoded);
}

function delUser(id){
	var list = getUsers();
	if( list[id] ){
		delete list[id];
	}
	setDatas(list);
}

$(document).ready(function() {
	$.initializeLogin();
	initUsers();
});

function initUsers(){
	var list = getUsers();
	var html = '';
	$.each(list, function(i, n){
		html += '<a data-id="'+i+'" data-username="'+n.heivrid+'" data-authcode="'+n.authcode+'" data-realname="'+n.name+'" data-avatar="avatar.php?img=yes&heivrid='+n.heivrid+'" href="javascript:void(0);" class="avatar pin"></a>';
	});
	if( !html ){
		$('.plus').click();
	}else{
		$('#avatars').html(html);
		$(".avatar").each(function() {
			var source = $(this).attr("data-avatar");
			$(this).css("background-image", "url("+ source +")");
		});
	}
}

function getcookie(name) {
    var cookie_start = document.cookie.indexOf(name);
    var cookie_end = document.cookie.indexOf(";", cookie_start);
    return cookie_start == -1 ? '': unescape(document.cookie.substring(cookie_start + name.length + 1, (cookie_end > cookie_start ? cookie_end: document.cookie.length)));
}
function setcookie(cookieName, cookieValue, seconds, path, domain, secure) {
    var expires = new Date();
    expires.setTime(expires.getTime() + seconds);
    document.cookie = escape(cookieName) + '=' + escape(cookieValue) + (expires ? '; expires=' + expires.toGMTString() : '') + (path ? '; path=' + path: '/') + (domain ? '; domain=' + domain: '') + (secure ? '; secure': '');
}
